import { createRouter, createWebHistory } from "vue-router";
import { UseUIStore } from "@/store/UI";
import verify from '@/utils/verify.js'
import { getToken } from "@/utils/auth";

const route = createRouter({
    history: createWebHistory('/f'),
    routes: [],
})

const modules = import.meta.glob('./view/**/*/route.config.js', { eager: true });
for (const key in modules) {
    if (verify.is(modules[key].default, 'array')) {
        modules[key].default.forEach(item => {
            route.addRoute(item);
        })
    }
}
// route.addRoute({ path: '/:pathMatch(.*)', redirect: '/404' });

const routeStack = {};
route.beforeEach(async (to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title
    } else {
        document.title = import.meta.env.VITE_APP_TITLE
    }
    const UIStore = UseUIStore();
    if (!routeStack.hasOwnProperty(to.path)) { // 前进,向左滑动 
        routeStack[to.path] = '';
        UIStore.RouteState = 'slide-left';
    } else if (routeStack.hasOwnProperty(from.path)) {// 后退,向右滑动
        delete routeStack[from.path]
        UIStore.RouteState = 'slide-right';
    } else {// 同一层级,无动画
        routeStack[to.path] = '';
        UIStore.RouteState = 'none';
    }
    if (to.meta.whiteList) {
        next();
    } else {
        const token = getToken();
        if (token) {
            next();
        } else {
            next('/login')
        }
    }
});


export default route